package callback.asyn;

import util.MathUtil;

/**
 *
 *
 *
 */
public class AsyncCallback {

}

// Java program to illustrate Asynchronous main.java.callback

interface OnGeekEventListener {

    /**
     * this can be any type of method
     * 回调方法
     */
    void onGeekEvent();
}

class A implements OnGeekEventListener {

    @Override
    public void onGeekEvent()
    {
        System.out.println("Performing main.java.callback after Asynchronous Task");
    }
}

class B {

    /**
     * listener field
     * 也可以不用接口声明对象，
     * 所谓
     */
    private OnGeekEventListener mListener;

    // setting the listener
    public void registerOnGeekEventListener(OnGeekEventListener mListener)
    {
        this.mListener = mListener;
    }

    // My Asynchronous task
    public void doGeekStuff()
    {

        // An Async task always executes in new main.java.thread
        //noinspection AlibabaAvoidManuallyCreateThread
        new Thread(() -> {

            // perform any operation
            System.out.println("Performing operation in Asynchronous Task");

            // 模拟耗时操作
            MathUtil.resolvePrime();

            // check if listener is registered.
            if (mListener != null) {

                // invoke the main.java.callback method of class A
                mListener.onGeekEvent();
            }
        }).start();
    }

    // Driver Program
    public static void main(String[] args)
    {

        B obj = new B();
        OnGeekEventListener mListener = new A();
        obj.registerOnGeekEventListener(mListener);
        obj.doGeekStuff();
    }
}



